/*
 *
 * This is a VoIP Application designed for local-network usage for voice and
 * messaging
 * Copyright (C) 2012  Imran M Yousuf (imyousuf@smitsol.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.smitsol.voip.server;

import com.smitsol.voip.server.sip.Headers;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.sip.SipServlet;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author imyousuf
 */
public class SmartVoIPServlet extends SipServlet {

  private final Logger logger = LoggerFactory.getLogger(getClass());

  @Override
  protected void doRequest(SipServletRequest request) {
    logger.info("handling request: {}", request.getMethod() + " " + request.getRequestURI());
    try {
      super.doRequest(request);
    }
    catch (Exception e) {
      logger.warn("Failed to handle request: \n" + request, e);
    }
  }

  @Override
  protected void doInvite(SipServletRequest req) throws ServletException, IOException {
    getServletContext().getNamedDispatcher("smart-voip-proxy").forward(req, null);
  }

  @Override
  protected void doMessage(SipServletRequest req) throws ServletException, IOException {
    getServletContext().getNamedDispatcher("smart-voip-proxy").forward(req, null);
  }

  @Override
  protected void doRegister(SipServletRequest req) throws ServletException, IOException {
    getServletContext().getNamedDispatcher("smart-voip-registrar").forward(req, null);
  }

  @Override
  protected void doSubscribe(SipServletRequest req) throws ServletException, IOException {
    String event = req.getHeader(Headers.EVENT);
    if ("reg".equals(event)) {
      doRegister(req);
    }
    else if ("presence".equals(event) ||
        "presence.winfo".equals(event)) {
      getServletContext().getNamedDispatcher("smart-voip-presence").forward(req, null);
    }
    else {
      SipServletResponse response = req.createResponse(SipServletResponse.SC_BAD_EVENT);
      response.addHeader(Headers.ALLOW_EVENTS, "reg");
      response.addHeader(Headers.ALLOW_EVENTS, "presence");
      response.addHeader(Headers.ALLOW_EVENTS, "presence.winfo");
      response.send();
      response.getApplicationSession().invalidate();
    }
  }
}
